package top.rainf.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.rainf.constants.UserConstants;
import top.rainf.mapper.RegisterMapper;
import top.rainf.mapper.UserPersonalInfoMapper;
import top.rainf.service.IRegisterService;
import top.rainf.support.Result;
import top.rainf.util.MD5Util;
import top.rainf.util.StringUtil;
import top.rainf.domain.vo.UserBaseInfo;
import top.rainf.domain.vo.UserPersonalInfo;

/**
 * @author 星环
 * @date 2023/5/7 15:43:34
 * @description
 */
@Service
public class RegisterService implements IRegisterService {
    @Autowired
    RegisterMapper registerMapper;

    @Autowired
    UserPersonalInfoMapper userPersonalInfoMapper;

    /**
     * 注册用户服务    验证用户名唯一、验证码。将密码转为MD5，需要事务同时加入baseinfo和个性信息
     * @param user
     * @param verifyCode
     * @param realCode
     * @return
     */
    public String register(UserBaseInfo user,String verifyCode,String realCode){
        System.out.println(123);
        boolean unique = checkUsernameUnique(user.getUsername());
        if (!unique){
            return "用户名已存在！试试新的吧";
        }
        //验证 验证码
        Result codeSame = validateVerifyCode(verifyCode,realCode);
        System.out.println(verifyCode + "  " + realCode);
        if(codeSame.getCode() == Result.FAILED){
            return "验证码不正确，请重新输入！";
        }
        //加密密码
        String encodePwd = MD5Util.encode(user.getPassword());
        user.setPassword(encodePwd);
        //之后要存入session
        user.setUserGroupId(UserConstants.USER_GROUP_USER);
        //用户个性信息，全部默认，只需要填入id就行，为了分表
        boolean saved = createUser(user);
        return saved ? "" : "存储失败！";
    }

    boolean createUser(UserBaseInfo userBaseInfo){
        int base = registerMapper.insertUserBaseInfo(userBaseInfo);
        System.out.println(userBaseInfo.getId());
        UserPersonalInfo userPersonalInfo = new UserPersonalInfo();
        userPersonalInfo.setUserId(userBaseInfo.getId());
        int personal = userPersonalInfoMapper.insertUserPersonalInfo(userPersonalInfo);
        return base == 1 && personal == 1;
    }


    @Override
    public boolean checkUsernameUnique(String username) {
        if(StringUtil.isNullOrEmpty(username)){
            return false;
        }
        UserBaseInfo userBaseInfo = registerMapper.checkUsernameUnique(username);
        return userBaseInfo == null;
    }


    public Result validateVerifyCode(String verifyCode, String realCode) {
        if(StringUtil.isNullOrEmpty(verifyCode) || StringUtil.isNullOrEmpty(realCode)){
            return Result.fail("服务内验证码为空，失败");
        }
        boolean isEqual = realCode.equals(verifyCode);
        return isEqual ? Result.success() : Result.fail();
    }
}
